package net.test;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

public class test11_getimg {

    public static void main(String[] args) {
        String url = "http://www.taobao.com";  // 目标网站URL
        fetchImages(url);
    }

    private static void fetchImages(String url) {
        try {
            // 连接到网站并获取文档
            Document doc = Jsoup.connect(url).get();
            // 使用CSS选择器查找所有图片元素
            Elements allImages = doc.select("img[src~=(?i)\\.(png|jpe?g|gif|svg|bmp)], [style*='background-image'], img[data-src]");

            // 循环处理每一个图片元素
            for (Element img : allImages) {
                String src = img.absUrl("src");  // 获取绝对路径URL
                downloadImage(src);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void downloadImage(String src) {
        try {
            URL url = new URL(src);
            InputStream in = url.openStream();
            String fileName = src.substring(src.lastIndexOf('/') + 1);
            OutputStream out = new BufferedOutputStream(Files.newOutputStream(Paths.get("imgs/" + fileName)));

            // 读取图片数据并保存
            for (int b; (b = in.read()) != -1;) {
                out.write(b);
            }
            out.close();
            in.close();
            System.out.println("Image downloaded: " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
